package com.juzhencms.apps.busi.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.DictionaryService;
import com.juzhencms.apps.busi.service.MenuService;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/newsCategory")
@Slf4j
public class NewsCategoryController  extends BaseController{
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private DictionaryService dictionaryService;
	
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		int site_id = 0;
		String name = "";
		
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 ";		
	
		String sortField="position";
		String sortOrder="asc";
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name,pid as parentId,position,publish,create_time from "+DBTable.newsCategory+" "+where+" order by "+sortField+" "+sortOrder+",create_time asc", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
			}
		}
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.newsCategory+" where id=?",new Object[]{id});	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) (record.get("create_time")==null?"":record.get("create_time"));
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null && !"0".equals(data.get("id").toString())){
			id=data.get("id").toString();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		if(id==null || id.equals("")){
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				data.put("create_time", sdf.format(date));
			}
			Map prevMenu=this.getCommonService().getJdbcDao().queryRow("select position from "+DBTable.newsCategory+" where del_flag=0 and pid=? order by position desc limit 1",new Object[]{data.get("pid").toString()});	
			int position = 0;
			if(prevMenu!=null) {
				 position = Integer.parseInt(prevMenu.get("position").toString());
			}
			data.put("position", position+1);
			data.put("create_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().addObj(DBTable.newsCategory, data);
		}else{
			data.put("update_time", sdf.format(date));
			data.put("update_user", this.getLoginUserId());
			this.getCommonService().getJdbcDao().updateObj(DBTable.newsCategory, data, "id");
		}
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.newsCategory+" set del_flag=1,update_time=NOW() where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	@RequestMapping(value="/getParentTreeMenuList/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getParentTreeMenuList(@PathVariable("id") String id,HttpServletRequest request){
		if(id==null || "".equals(id) || "undefined".equals(id)) {
			id="0";
		}
		List dataList=this.getEditParentMenuTree(new Integer(id), 0);
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/getTreeMenuList",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getTreeMenuList(HttpServletRequest request){
		
		List dataList=this.getMenuTree(0);
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	private List getEditParentMenuTree(int id,int pid){
		//System.out.println(id);
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.newsCategory+" where pid=? and del_flag = 0 order by position asc,id asc",new Object[]{pid});
		for(int i=0;i<dataList.size();i++){
			Map menu=(Map)dataList.get(i);
			if(menu.get("id").toString().equals(""+id)){
				//menu.put("chkDisabled",true);
				//System.out.println(id);
			}else{
				List subList=this.getEditParentMenuTree(id, new Integer(menu.get("id").toString()));
				if(subList!=null && subList.size()>0)
					menu.put("children", subList);
			}
		}
		return dataList;
	}
	
	private List getMenuTree(int pid){
		//System.out.println(id);
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.newsCategory+" where pid=? and del_flag = 0 order by position asc,id asc",new Object[]{pid});
		for(int i=0;i<dataList.size();i++){
			Map menu=(Map)dataList.get(i);
			List subList=this.getMenuTree(new Integer(menu.get("id").toString()));
			if(subList!=null && subList.size()>0)
				menu.put("children", subList);
		}
		return dataList;
	}
	
	@RequestMapping(value="/getSiteMenuTreeList",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getSiteMenuTreeList(HttpServletRequest request){
		
		List dataList=new ArrayList();
		//查询所有站点数据
		List siteList=this.getCommonService().getJdbcDao().querySql("select concat('s',id) as id,0 as pId,name,'' as module from "+DBTable.site+" where del_flag=0 order by position asc,id asc");
		dataList.addAll(siteList);
		
		//查询一级栏目节点
		List pMenuList=this.getCommonService().getJdbcDao().querySql("select id,concat('s',site_id) as pId,name,module from "+DBTable.newsCategory+" where parent_id=0 and del_flag=0 order by position asc,id asc");
		dataList.addAll(pMenuList);
		
		List menuList=this.getCommonService().getJdbcDao().querySql("select id,parent_id as pId,name,module from "+DBTable.newsCategory+" where parent_id>0 and del_flag=0 order by position asc,id asc");
		dataList.addAll(menuList);
		
		
		Map data=new HashMap();
		data.put("data", dataList.toArray());
		
		return WebUtil.resultString(data,request);
	}
	
	
	private Map getMenuTreeData(int site_id, int parent_id, String whereStr) {
		// TODO Auto-generated method stub
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and site_id= ? and parent_id=? ";
		whereParamList.add(site_id);
		whereParamList.add(parent_id);
		if(whereStr!=null && !whereStr.trim().equals("")){
			where+=" and "+whereStr;
		}
		where+=" order by position asc";
		
		List moduleVars=dictionaryService.getDictionaryItemList("moduleVars");
		
		List menuList = this.getCommonService().getJdbcDao().querySql("select id,name as text,module,publish,template,link_url from " + DBTable.newsCategory
				+ where, whereParamList.toArray());
		if (menuList != null && menuList.size() > 0) {
			for (int i = 0; i < menuList.size(); i++) {
				Map row = (Map) menuList.get(i);
				
				String extAttrString="";
				List extAttrList=new ArrayList();
				
				if(row.get("module")!=null && !row.get("module").equals("")){
					extAttrList.add("功能:"+dictionaryService.getText(moduleVars,row.get("module").toString()));
					
				}
				if(row.get("template")!=null && !row.get("template").equals("")){
					extAttrList.add("模板:"+row.get("template"));
				}
				if(row.get("link_url")!=null && !row.get("link_url").equals("")){
					extAttrList.add("链接:"+row.get("link_url"));
				}
				
				if(row.get("publish")!=null && row.get("publish").toString().equals("0")){
					extAttrList.add("未发布");
				}
				
				for(int a=0;a<extAttrList.size();a++) {
					if(a<extAttrList.size()-1) {
						extAttrString+=extAttrList.get(a)+",";
					}else {
						extAttrString+=extAttrList.get(a);
					}
				}
				
				
				if(!extAttrString.equals("")){
					row.put("text", row.get("text").toString()+" ["+extAttrString+"]");
				}
				
				
				Map tmp = this.getMenuTreeData(site_id,new Integer(row.get("id").toString()),whereStr);
				if (tmp != null)
					row.put("nodes", tmp.get("nodes"));
			}
			Map data = new HashMap();
			data.put("nodes", menuList);
			return data;
		} else {
			return null;
		}
	}
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.newsCategory+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	
	
	

	
}
